const router = require('koa-router')();
const DB = require('../../module/db.js');
const tools = require('../../module/tools.js');
const multer = require('koa-multer');



// 配置图片上传目录
const storage = multer.diskStorage({
	destination: function(req, file, cb){
		cb(null, 'static/upload')
	},
	filename: function(req, file, cb){
		let fileFormat = (file.originalname).split('.');

		// 需要处理上传的文件命名（这里要填上后缀，不然koa-multer会丢失后缀名）
		cb(null, file.fieldname + '-' + Date.now() + '.' + fileFormat[fileFormat.length - 1]);

		//cb(null, file.fieldname + '-' + Date.now())
	}
});
const upload = multer({storage: storage});
// const upload = multer({dest: 'upload/'});


router.get('/', async (ctx) => {
	
	let pageindex = (ctx.query.page) ? parseInt(ctx.query.page, 0) : 1;
	let pageSize = (ctx.query.size) ? parseInt(ctx.query.size, 0) : 10;
	let result = await DB.findOne('article', {}, {
		index: pageindex,
		size: pageSize,
        sort: {
            create_time: -1
        }
	});
	
	let countNum = await DB.count('article', {});
	
    await ctx.render('admin/article/list', {
    	list: result,
    	pageIndex: pageindex,
    	totalPages: Math.ceil(countNum / pageSize),
    });
});



router.get('/add', async (ctx) => {
	
	// 查询分类数据
	let cateList = await DB.findOne('articlecate', {});

	cateList = tools.cateToList(cateList);

    await ctx.render('admin/article/add', {
        cateList
	});
});

router.post('/add', upload.single('img_url'), async (ctx) => {

    let pid = ctx.req.body.pid;
    let title = ctx.req.body.title.trim();
    let keywords = ctx.req.body.keywords.trim();
    let catename = ctx.req.body.catename.trim();
    let author = ctx.req.body.author.trim();
    let status = (ctx.req.body.status) ? parseInt(ctx.req.body.status, 0) : 0;
    let is_best = ctx.req.body.is_best;
    let is_hot = ctx.req.body.is_hot;
    let is_new = ctx.req.body.is_new;
    let description = ctx.req.body.description.trim();
	let content = ctx.req.body.content ? ctx.req.body.content.trim().trim() : '';
    let img_url = ctx.req.file ? ctx.req.file.path.replace('static\\', "") : ''; // 返回文件名
	let sort = 0;


    let addResult = await DB.insertOne('article', {
        pid,
        title,
        catename,
        description,
        content,
        img_url,
        sort,
        create_time: new Date(),
        last_time: new Date(),
        author,
        keywords,
        status,
        is_best,
        is_hot,
        is_new
    });

    ctx.redirect(ctx.state.__HOST__ + '/admin/article');
});



router.get('/edit', async (ctx) => {

	let id = ctx.query.id;

    // 查询分类数据
    let cateList = await DB.findOne('articlecate', {});
    let cateResult = tools.cateToList(cateList);

	let articleList = await DB.findOne('article', {
		_id: DB.getObjectID(id)
	});
	
    await ctx.render('admin/article/edit', {
        cateList: cateResult,
		list: articleList[0],
        referer: ctx.state.G.referer
    });
});

router.post('/edit', upload.single('img_url'), async (ctx) => {
	let id = ctx.req.body.id;
    let img_url = ctx.req.file ? ctx.req.file.path.replace('static\\', '') : ''; // 返回文件名
    let referer = ctx.req.body.referer || '';
    
	let json = {
		pid: ctx.req.body.pid,
	    title: ctx.req.body.title.trim(),
	    keywords: ctx.req.body.keywords.trim(),
	    catename: ctx.req.body.catename.trim(),
	    author: ctx.req.body.author.trim(),
	    status: (ctx.req.body.status) ? parseInt(ctx.req.body.status, 0) : 0,
	    is_best: ctx.req.body.is_best,
	    is_hot: ctx.req.body.is_hot,
	    is_new: ctx.req.body.is_new,
	    description: ctx.req.body.description.trim(),
	    content: ctx.req.body.content ? ctx.req.body.content.trim().trim() : '',
	    last_time: new Date()
	};
	
	if(img_url){
		json['img_url'] = img_url;
	}

    let addResult = await DB.updateOne('article', {
    	_id: DB.getObjectID(id)
	}, json);

    (referer) ? ctx.redirect(referer) : ctx.redirect(ctx.state.__HOST__ + '/admin/article');

});


router.get('/delete', async (ctx) => {

    ctx.body = '删除用户';
});

module.exports = router.routes();